package com.yiyi.user.controller;


import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yiyi.common.annotation.Log;
import com.yiyi.common.core.controller.BaseController;
import com.yiyi.common.core.domain.AjaxResult;
import com.yiyi.common.core.page.TableDataInfo;
import com.yiyi.common.enums.BusinessType;
import com.yiyi.common.utils.poi.ExcelUtil;
import com.yiyi.user.domain.CustomerInfo;
import com.yiyi.user.domain.Measure;
import com.yiyi.user.domain.OrderInfo;
import com.yiyi.user.domain.SysJson;
import com.yiyi.user.service.ICustomerInfoService;
import com.yiyi.user.service.IOrderInfoService;
import com.yiyi.user.service.ISysJsonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 客户管理Controller
 *
 * @author yiyi
 * @date 2024-09-24
 */
@RestController
@RequestMapping("/customer/customer")
public class CustomerInfoController extends BaseController {
    @Autowired
    private ICustomerInfoService customerInfoService;

    @Autowired
    private ISysJsonService sysJsonService;

    @Autowired
    private IOrderInfoService orderInfoService;


    /**
     * 查询客户管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CustomerInfo customerInfo) {
        startPage();
        List<CustomerInfo> list = customerInfoService.selectCustomerInfoList(customerInfo);
        return getDataTable(list);
    }

    /**
     * 导出客户管理列表
     */
    @Log(title = "客户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CustomerInfo customerInfo) {
        List<CustomerInfo> list = customerInfoService.selectCustomerInfoList(customerInfo);
        ExcelUtil<CustomerInfo> util = new ExcelUtil<CustomerInfo>(CustomerInfo.class);
        util.exportExcel(response, list, "客户管理数据");
    }

    /**
     * 获取客户管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(customerInfoService.selectCustomerInfoById(id));
    }

    /**
     * 根据订单编号获取 客户信息
     * @return
     */
    @GetMapping(value = "/getCustomerInfoByOrderNum")
    public AjaxResult getCustomerInfoByOrderNum(CustomerInfo customerInfo) {
        CustomerInfo qryCustomerInfo=customerInfoService.getCustomerInfoByOrderNum(customerInfo);
        return success(qryCustomerInfo);
    }

    /**
     * 新增客户管理
     */
    @Log(title = "客户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CustomerInfo customerInfo) {
        return toAjax(customerInfoService.insertCustomerInfo(customerInfo));
    }

    /**
     * 修改客户管理
     */
    @Log(title = "客户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CustomerInfo customerInfo) {
        return toAjax(customerInfoService.updateInfo(customerInfo));
    }

    /**
     * 删除客户管理
     */
    @Log(title = "客户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(customerInfoService.deleteCustomerInfoByIds(ids));
    }

    /**
     * 测算
     */
    @PostMapping("/measure")
    public AjaxResult measure(@RequestBody Measure measure) {
        StringBuilder resultText = new StringBuilder();

        // 请求第三方测算api
        measure.setAppKey("hRHoA7J8Hg7gu6lpySWpMy0iN");
        String custr = JSONObject.toJSONString(measure);
        String result2 = HttpRequest.post("https://apidoc.sanqizhouyi.com:82/api/bzjp")
                .body(custr)
                .execute().body();

        // 解析 JSON
        JSONObject data = JSONObject.parseObject(result2).getJSONObject("data").getJSONObject("data");
        JSONObject dandata = JSONObject.parseObject(result2).getJSONObject("data");


        /** 喜用神*/
        JSONObject xiyongshen = data.getJSONObject("xiyongshen");
        // 提取信息
        String xishen = xiyongshen.getJSONObject("data").getString("xishen");
        String shiye = xiyongshen.getString("shiye");
        JSONArray sanheArray = xiyongshen.getJSONObject("sanhe").getJSONArray("sanhe");
        // 生成富文本
        StringBuilder richTextBuilder = new StringBuilder();
        richTextBuilder.append("<h2>喜用神</h2>");
        richTextBuilder.append("<p>").append(xishen).append("</p>");
        richTextBuilder.append("<h2>事业建议</h2>");
        richTextBuilder.append("<p>").append(shiye).append("</p>");
        richTextBuilder.append("<h2>三合动物</h2>");
        richTextBuilder.append("<ul>");
        for (int i = 0; i < sanheArray.size(); i++) {
            richTextBuilder.append("<li>").append(sanheArray.getString(i)).append("</li>");
        }
        richTextBuilder.append("</ul>");
        resultText.append(richTextBuilder.toString());

        /** 综合*/
        JSONObject zonghe = data.getJSONObject("zonghe");
        // 提取信息
        String sx = zonghe.getString("sx");
        String yx = zonghe.getString("yx");
        String qd = zonghe.getString("qd");
        String lncy = zonghe.getString("lncy");
        String xtcy = zonghe.getString("xtcy");
        String zhuyi = zonghe.getString("zhuyi");
        String aqfx = zonghe.getString("aqfx");
        // 创建富文本 HTML
        StringBuilder zongheRichText = new StringBuilder();
        zongheRichText.append("<br><h1>生肖: ").append(sx).append("</h1>");
        zongheRichText.append("<br><h2>性格特征</h2><p>").append(yx).append("</p>");
        zongheRichText.append("<h2>情感特点</h2><p>").append(qd).append("</p>");
        zongheRichText.append("<h2>流年财运</h2><p>").append(lncy).append("</p>");
        zongheRichText.append("<br><h2>生肖财运分析</h2><p>").append(xtcy).append("</p>");
        zongheRichText.append("<h2>注意事项</h2><p>").append(zhuyi).append("</p>");
        zongheRichText.append("<h2>爱情分析</h2><p>").append(aqfx).append("</p>");
        resultText.append(zongheRichText.toString());

        /** 用户基本信息*/
        JSONObject user = dandata.getJSONObject("user");
        // 提取信息
        String xing = user.getJSONObject("xingming").getString("xing");
        String ming = user.getJSONObject("xingming").getString("ming");
        String sex = user.getString("sex");
        String usersx = user.getString("sx");
        JSONObject nianling = user.getJSONObject("nianling");
        String year = nianling.getString("y");
        String month = nianling.getString("m");
        String day = nianling.getString("d");
        String hour = nianling.getString("h");
        String minute = nianling.getString("i");
        JSONObject jiuli = user.getJSONObject("jiuli");
        String jiuliYear = jiuli.getString("y");
        String jiuliMonth = jiuli.getString("m");
        String jiuliDay = jiuli.getString("d");
        String jiuliHour = jiuli.getString("h");
        String[] bazi = user.getJSONArray("bazi").toArray(new String[0]);
        String[] wh = user.getJSONArray("wh").toArray(new String[0]);
        String lDate = user.getString("lDate");
        // 创建富文本 HTML
        StringBuilder richText = new StringBuilder();
        richText.append("<h1>用户信息</h1>");
        richText.append("<p>姓名: ").append(xing).append(" ").append(ming).append("</p>");
        richText.append("<p>性别: ").append(sex).append("</p>");
        richText.append("<p>生肖: ").append(usersx).append("</p>");
        richText.append("<p>出生日期: ").append(year).append("年").append(month).append("月").append(day).append("日 ")
                .append(hour).append("时").append(minute).append("分</p>");
        richText.append("<p>九里: ").append(jiuliYear).append("年").append(jiuliMonth).append("月")
                .append(jiuliDay).append("日 ").append(jiuliHour).append("时</p>");
        richText.append("<h2>八字</h2><p>");
        for (String b : bazi) {
            richText.append(b).append(" ");
        }
        richText.append("</p>");
        richText.append("<h2>五行</h2><p>");
        for (String w : wh) {
            richText.append(w).append(" ");
        }
        richText.append("</p>");
        richText.append("<p>详细时间: ").append(lDate).append("</p>");
        // 输出富文本
        resultText.append(richText.toString());


        /** 八字信息*/
      /*  JSONObject info = dandata.getJSONObject("info");
        StringBuilder richTextinfo = new StringBuilder();
        // 处理 jmsh
        JSONObject jmsh = info.getJSONObject("jmsh");
        richTextinfo.append("<h2>五行综述</h2>");
        richTextinfo.append("<ul>");
        jmsh.forEach((key, value) -> richTextinfo.append("<li>").append(key).append(": ").append(value).append("</li>"));
        richTextinfo.append("</ul>");
        // 处理 wharr
        JSONObject wharr = info.getJSONObject("wharr");
        richTextinfo.append("<h2>五行健康</h2>");
        richTextinfo.append("<p>旺: ").append(wharr.getString("wang")).append("</p>");
        richTextinfo.append("<p>缺: ").append(wharr.getString("que")).append("</p>");
        JSONObject whjk = wharr.getJSONObject("whjk");
        richTextinfo.append("<ul>");
        whjk.forEach((key, value) -> richTextinfo.append("<li>").append(key).append(": ").append(value).append("</li>"));
        richTextinfo.append("</ul>");
        // 处理 nayin
        JSONArray nayinArray = info.getJSONArray("nayin");
        richTextinfo.append("<h2>四柱纳音</h2>");
        richTextinfo.append("<ul>");
        for (int i = 0; i < nayinArray.size(); i++) {
            JSONObject nayin = nayinArray.getJSONObject(i);
            richTextinfo.append("<li>ID: ").append(nayin.getInteger("id"))
                    .append(", Jiazi: ").append(nayin.getString("jiazi"))
                    .append(", Layin: ").append(nayin.getString("layin")).append("</li>");
        }
        richTextinfo.append("</ul>");
        // 最终输出富文本
        resultText.append(richTextinfo.toString());*/


        /** 生肖个性*/
        JSONObject sxgx = dandata.getJSONObject("sx");
        // 构建富文本
        StringBuilder richTextsxgx = new StringBuilder();
        richTextsxgx.append("<h2>运势信息</h2>");
        richTextsxgx.append("<ul>");
        JSONArray yfArraysxgx = sxgx.getJSONArray("yf");
        for (int i = 0; i < yfArraysxgx.size(); i++) {
            JSONObject yf = yfArraysxgx.getJSONObject(i);
            richTextsxgx.append("<li>")
                    .append("<strong>").append(yf.getString("title")).append("</strong><br>")
                    .append("内容: ").append(yf.getString("content")).append("<br>")
                    .append("内 容: ").append(yf.getString("neirong")).append("<br>")
                    .append("流年: ").append(yf.getString("liunian")).append("<br>")
                    .append("主 题: ").append(yf.getString("toubu2"))
                    .append("</li>");
        }
        richTextsxgx.append("</ul>");
        // 输出结果
        resultText.append(richTextsxgx.toString());


        /** 四柱信息*/
        JSONObject pp = dandata.getJSONObject("pp");
        // 构建富文本格式
        StringBuilder richTextpp = new StringBuilder();
        richTextpp.append("<br><h2>四柱信息</h2>");
        richTextpp.append("<ul>")
                .append("<li><strong>胎元:</strong> ").append(pp.getString("taiyuan")).append("</li>")
                .append("<li><strong>纳音胎元:</strong> ").append(pp.getString("nayintaiyuan")).append("</li>")
                .append("<li><strong>命宫:</strong> ").append(pp.getString("minggong")).append("</li>")
                .append("<li><strong>时神:</strong> ").append(pp.getString("shishen")).append("</li>")
                .append("<li><strong>日元:</strong> ").append(pp.getString("riyuan")).append("</li>")
                .append("<li><strong>四柱:</strong> ").append(pp.getString("sizhu")).append("</li>")
                .append("<li><strong>阳刃:</strong> ").append(pp.getString("ygz")).append("</li>")
                .append("<li><strong>月干:</strong> ").append(pp.getString("mgz")).append("</li>")
                .append("<li><strong>日干:</strong> ").append(pp.getString("rgz")).append("</li>")
                .append("<li><strong>时干:</strong> ").append(pp.getString("hgz")).append("</li>")
                .append("<li><strong>相关干支:</strong> ").append(pp.getString("xkrgz")).append("</li>")
                .append("<li><strong>纳音命宫:</strong> ").append(pp.getString("nayinminggong")).append("</li>")
                .append("</ul>");

        // 输出结果
        resultText.append(richTextpp.toString());

        // 解析各部分数据
        JSONObject rglm = dandata.getJSONObject("rglm");
        JSONObject sxth = dandata.getJSONObject("sxth");
        JSONObject cookies = dandata.getJSONObject("cookies");
        // 构建富文本格式
        StringBuilder zhrichText = new StringBuilder();
        zhrichText.append("<br><h2>个人信息</h2>")
                .append("<ul>")
                .append("<li><strong>姓名:</strong> ").append(cookies.getJSONObject("xingming").getString("xing"))
                .append(cookies.getJSONObject("xingming").getString("ming")).append("</li>")
                .append("<li><strong>性别:</strong> ").append(cookies.getString("sex")).append("</li>")
                .append("<li><strong>生肖:</strong> ").append(cookies.getString("sx")).append("</li>")
                .append("<li><strong>年龄:</strong> ").append(cookies.getJSONObject("nianling").getString("nl")).append("</li>")
                .append("<li><strong>出生日期:</strong> ").append(cookies.getString("lDate")).append("</li>")
                .append("<li><strong>四柱:</strong> ").append(String.join(", ", cookies.getJSONArray("bazi").toJavaList(String.class))).append("</li>")
                .append("<li><strong>五行:</strong> ").append(String.join(", ", cookies.getJSONArray("wh").toJavaList(String.class))).append("</li>")
                .append("</ul>");
        zhrichText.append("<br><h2>日干信息</h2>")
                .append("<ul>")
                .append("<li><strong>日干:</strong> ").append(rglm.getString("rgz")).append("</li>")
                .append("<li><strong>日干信息:</strong> ").append(rglm.getString("rgxx")).append("</li>")
                .append("<li><strong>日干测算:</strong> ").append(rglm.getString("rgcz")).append("</li>")
                .append("<li><strong>性格分析:</strong> ").append(rglm.getString("aqfx")).append("</li>")
                .append("<li><strong>事业分析:</strong> ").append(rglm.getString("syfx")).append("</li>")
                .append("<li><strong>财运分析:</strong> ").append(rglm.getString("cyfx")).append("</li>")
                .append("<li><strong>健康分析:</strong> ").append(rglm.getString("jkfx")).append("</li>")
                .append("</ul>");
        zhrichText.append("<br><h2>生肖特征</h2>")
                .append("<ul>")
                .append("<li><strong>日:</strong> ").append(sxth.getString("ri")).append("</li>")
                .append("<li><strong>时:</strong> ").append(sxth.getString("shi")).append("</li>")
                .append("</ul>");
        // 输出结果
        resultText.append(zhrichText.toString());

        // 判断库内是否存在该 订单 的记录
        SysJson selectSysJson = new SysJson();
        selectSysJson.setOrderNumber(measure.getOrderNumber());
        SysJson json = sysJsonService.getJsonByOrderNum(selectSysJson);
        if (json == null){
            //保存客户测算结果
            SysJson sysJson = new SysJson();
            // 客户id
            sysJson.setOrderNumber(measure.getOrderNumber());
            //测算结果
            sysJson.setJsonResult(resultText.toString());
            // 原测算结果
            sysJson.setJson(result2);
            sysJsonService.insertSysJson(sysJson);

            // 根据订单编号 保存该客户的测算在线查询地址
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrderNumber(measure.getOrderNumber());
            orderInfo.setResulAddress(measure.getResulAddress());
            orderInfoService.notify(orderInfo);
        }

        return success(result2);
    }

    /**
     * 喜用神
     * @param xishen
     * @param shiye
     * @param sanheArray
     * @return
     */
    private static String xiyongshenConvertToRichText(String xishen, String shiye, JSONArray sanheArray) {
        StringBuilder richTextBuilder = new StringBuilder();

        richTextBuilder.append("<h2>喜用神</h2>");
        richTextBuilder.append("<p>").append(xishen).append("</p>");

        richTextBuilder.append("<h2>事业建议</h2>");
        richTextBuilder.append("<p>").append(shiye).append("</p>");

        richTextBuilder.append("<h2>三合动物</h2>");
        richTextBuilder.append("<ul>");
        for (int i = 0; i < sanheArray.size(); i++) {
            richTextBuilder.append("<li>").append(sanheArray.getString(i)).append("</li>");
        }
        richTextBuilder.append("</ul>");

        return richTextBuilder.toString();
    }

}
